package com.example.bankend.service.method;



import com.example.bankend.mapper.CardMapper;
import com.example.bankend.mapper.DepositMapper;
import com.example.bankend.model.BankCard;
import com.example.bankend.model.Deposit;
import com.example.bankend.service.impl.DepositService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepositServiceImpl implements DepositService {
    @Autowired
    private DepositMapper depositMapper;
    @Autowired
    private CardMapper cardMapper;
    @Override
    public int insert(Deposit deposit) {
        return depositMapper.insert(deposit);
    }

    @Override
    public int deleteByPrimaryKey(Integer savingID) {
        return depositMapper.deleteByPrimaryKey(savingID);
    }

    @Override
    public int updateByPrimaryKey(Deposit deposit) {
        return depositMapper.updateByPrimaryKey(deposit);
    }

    @Override
    public Deposit selectByPrimaryKey(Integer savingID) {
        return depositMapper.selectByPrimaryKey(savingID);
    }
    //处理存取款
    @Override
    @Transactional
    public int processTransaction(String cardID, Double amount, String descrip, String savingName) {
        // 插入存款记录
        System.out.println(cardID + "  " + amount);
        Deposit deposit = new Deposit();
        deposit.setSavingName(savingName);
        deposit.setDescrip(descrip);
        int insertResult = depositMapper.insert(deposit);


        //验证卡状态
        BankCard card = cardMapper.selectByPrimaryKey(cardID);
        if (card == null) {
            throw new RuntimeException("卡不存在");
        }
        System.out.println(card.getIsReportLoss());
        if ("是".equals(card.getIsReportLoss())) {
            throw new RuntimeException("该卡正在挂失状态，您无权操作");
        }
        // 更新余额（存款为正，取款为负）
        int updateResult = 0;

        if ("存款".equals(savingName)) {
            updateResult = cardMapper.updateBalanceByCardID(cardID, amount);
        } else if ("取款".equals(savingName)) {
            // 检查余额是否足够

            if (card.getBalance() < amount) {
                throw new RuntimeException("余额不足");
            }
            updateResult = cardMapper.updateBalanceByCardID(cardID, -amount);
        }
        System.out.println(insertResult);
        System.out.println(updateResult);
        return insertResult + updateResult;
    }

    @Override
    public List<Deposit> selectAll() {
        return depositMapper.selectAll();
    }
}